package com.apy.module.network.util

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import com.apy.module.network.model.ApiResult
import retrofit2.HttpException
import java.io.IOException

object NetworkUtils {
    
    /**
     * Check if device is connected to the internet
     */
    fun isNetworkAvailable(context: Context): Boolean {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val network = connectivityManager.activeNetwork ?: return false
            val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
            
            capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
                    capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
                    capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
        } else {
            @Suppress("DEPRECATION")
            val networkInfo = connectivityManager.activeNetworkInfo
            networkInfo?.isConnected == true
        }
    }
    
    /**
     * Handle network errors and return appropriate error message
     */
    fun handleNetworkError(throwable: Throwable): String {
        return when (throwable) {
            is IOException -> "No network connection. Please check your internet connection."
            is HttpException -> {
                when (throwable.code()) {
                    401 -> "Unauthorized. Please login again."
                    403 -> "Access denied. You don't have permission to access this resource."
                    404 -> "Resource not found."
                    500 -> "Internal server error. Please try again later."
                    else -> "An error occurred. Please try again."
                }
            }
            else -> "An unexpected error occurred. Please try again."
        }
    }
    
    /**
     * Execute API call with error handling
     */
    suspend fun <T> safeApiCall(
        context: Context,
        apiCall: suspend () -> T
    ): ApiResult<T> {
        return if (isNetworkAvailable(context)) {
            try {
                ApiResult.Success(apiCall())
            } catch (throwable: Throwable) {
                ApiResult.Error(Exception(handleNetworkError(throwable)))
            }
        } else {
            ApiResult.Error(IOException("No network connection"))
        }
    }
}
